package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

@WebServlet("/RepeatVisitorServlet")
public class RepeatVisitorServlet extends HttpServlet {

	private static final long serialVersionUID = 3153469387723408146L;
	private static final String REPEAT_VISITOR = "repeatVisitor";
	private static final String REPEAT_VISITOR_CONFIRM = "yes";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		boolean newbie = true;
		
		Cookie[] cookies = req.getCookies();
		if(null != cookies){
			for(Cookie cookie : cookies){
				if(cookie.getName().equals(REPEAT_VISITOR) 
						&& cookie.getValue().equals(REPEAT_VISITOR_CONFIRM)
						){
					newbie = false;
					break;
				}
			}
		}
		//
		String title ;
		if(newbie){
			Cookie returnVisitorCookie = new Cookie(REPEAT_VISITOR, REPEAT_VISITOR_CONFIRM);
			returnVisitorCookie.setMaxAge(60);
			resp.addCookie(returnVisitorCookie);
			title = "Welcome Aboard.";
		}else{
			title = "Welcome Back.";
		}
		//
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		//
		out.println(Constants.docType + ServletUtilities.headWithTitle(title) +
				"<body><h1>" + title + "</h1></body></html>" 
				);
	}




	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}




	private static final Logger logger = 
			Logger.getLogger(RepeatVisitorServlet.class);
}
